<?
if (!defined('IN_RJ')) die("Error 404");
if (($_POST['ajaxtype']=="rating") && ($_POST['multi_id'] || $_POST['media_id']) && $_POST['star']) {
	$multi_id = intval($_POST['multi_id']);
	$media_id = intval($_POST['media_id']);
	$star = intval($_POST['star']);
	if($multi_id){
		$DB->query("UPDATE ".$conf['prefix']."multimedia SET multi_rating=multi_rating+{$star},multi_rating_total=multi_rating_total+1 WHERE multi_id={$multi_id}"); 
		$q = $DB->query("SELECT multi_rating, multi_rating_total FROM ".$conf['prefix']."multimedia WHERE multi_id = {$multi_id}");
		$qry = $DB->fetch_row($q);
		if ($qry['multi_rating_total'] =='0') $current_star = 0;
		else $rater_rating = $qry['multi_rating'] / $qry['multi_rating_total'];
	}
	elseif($media_id){
		$DB->query("UPDATE ".$conf['prefix']."media SET m_rating=m_rating+{$star},m_rating_total=m_rating_total+1 WHERE m_id={$media_id}"); 
		$q = $DB->query("SELECT m_rating, m_rating_total FROM ".$conf['prefix']."media WHERE m_id = {$media_id}");
		$qry = $DB->fetch_row($q);
		if ($qry['m_rating_total'] =='0') $current_star = 0;
		else $rater_rating = $qry['m_rating'] / $qry['m_rating_total'];
	}
	// Assign star image
	if ($rater_rating <= 0  ){$star1 = "none"; $star2 = "none"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 0.5){$star1 = "half"; $star2 = "none"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 1  ){$star1 = "full"; $star2 = "none"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 1.5){$star1 = "full"; $star2 = "half"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 2  ){$star1 = "full"; $star2 = "full"; $star3 = "none"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 2.5){$star1 = "full"; $star2 = "full"; $star3 = "half"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 3  ){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "none"; $star5 = "none";}
	if ($rater_rating >= 3.5){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "half"; $star5 = "none";}
	if ($rater_rating >= 4  ){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "full"; $star5 = "none";}
	if ($rater_rating >= 4.5){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "full"; $star5 = "half";}
	if ($rater_rating >= 5  ){$star1 = "full"; $star2 = "full"; $star3 = "full"; $star4 = "full"; $star5 = "full";}

	$show_rate="<img src=\"{TPL_LINK}/img/rate/".$star1.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star2.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star3.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star4.".gif\" border=0>"
		."<img src=\"{TPL_LINK}/img/rate/".$star5.".gif\" border=0>";
		if($multi_id)
			$show_rate.=" ( ".$qry['multi_rating_total']." {$lang['num_rate']} )";
		elseif($media_id)
			$show_rate.=" ( ".$qry['m_rating_total']." {$lang['num_rate']} )";
	echo $tpl->parse_tpl($show_rate);
		


}

if(($_POST['ajaxtype']=="player") && $_POST['movie_id'] && $_POST['epi_id']){
	$movie_id=intval($_POST['movie_id']);
	$epi_id=intval($_POST['epi_id']);
  	$player=$func->Get_player_epi($movie_id,$epi_id);
	echo $player;
}

if(($_POST['ajaxtype']=="player_fullscreen" || $_POST['ajaxtype']=="ytb_watch") && $_POST['movie_id'] && $_POST['epi_id']){
	$movie_id=intval($_POST['movie_id']);
	$epi_id=intval($_POST['epi_id']);

	  $repi=$DB->query("SELECT * FROM ".$conf['prefix']."media where m_id={$epi_id} and m_multimedia={$movie_id}");
  if($epi=$DB->fetch_row($repi)){
	  $re=$DB->query("SELECT * FROM ".$conf['prefix']."player where player_id={$epi['m_type']}");
	  $type=$DB->fetch_row($re);
	  if($_POST['ajaxtype']=="ytb_watch")
	  {		  
		 $player='<embed type="application/x-shockwave-flash" src="http://player.longtailvideo.com/player5.0.swf" style="" id="mpl" name="mpl" bgcolor="#000000" quality="high" allowscriptaccess="always" allowfullscreen="true" flashvars="&file='.$epi['m_url'].'&skin=http://www.longtailvideo.com/jw/upload/stylish.swf&volume=100&autostart=false&repeat=list" height="550" width="750">'; 
	  }
	  else{
		  if($type['player_use_xml'])  
			$url_file=$conf['web_url'].'/%3Fact=xml%26id='.$epi_id."%26type=2";
		  elseif($type['player_use_wpl'])  
			$url_file=$conf['web_url'].'/%3Fact=wpl%26id='.$epi_id."%26type=2";
		  else
			$url_file=($type['player_isgrab'])?$func->grab_link($func->unhtmlchars($epi['m_url'])):$func->unhtmlchars($epi['m_url']);  
					
			$player=$func->unhtmlchars(stripslashes($type['player_html']));
			$player=str_replace("{WEB_URL}",$conf['web_url']."/",$player);
			$player=str_replace("{URL}",$url_file,$player);
	  }
	}
	echo $player;
}


if(($_POST['ajaxtype']=="comment") && ($_POST['multi_id'] || $_POST['media_id'])){
	$multi_id=intval($_POST['multi_id']);
	$media_id=intval($_POST['media_id']);
	$cm_id=intval($_POST['cm_id']);
	$page=intval($_POST['page']);
	$level_admin=$func->check_level($_SESSION['ses_user_id']);
	if(!$page) $page=1;
	$number=intval($_POST['num_per']);
	if(!$number) $number=7;
	$content=$func->htmlchars($func->bad_words($func->text_2_html(substr(stripslashes(urldecode($_POST['comment_content'])),0,255))));
	$user_id=($logged_in)?$_SESSION['ses_user_id']:'';
	if($_POST['type']=="viewpage"){
			echo box_list_comment($multi_id,$media_id,$number,$page);
	}
	elseif($_POST['type']=="delete"){
			
			if($logged_in && $level_admin==1){
				if($DB->query("DELETE FROM ".$conf['prefix']."comment WHERE cm_id={$cm_id}"))
					echo $lang['deleted'];
				else echo $lang['error'];
			}
			else echo $lang['error'];
				echo "<br>".box_list_comment($multi_id,$media_id);
	}
	else{	      
    $timeout = 60;
	$time_wait= time() - $timeout;       
       if (isset($_SESSION["time_cm_post"]) && ($_SESSION["time_cm_post"] >=$time_wait )){
            echo "{$lang['wait_plz']} ".($_SESSION["time_cm_post"]-$time_wait)." {$lang['second']}!!";   
			
           return false;   
	  }   
      else{ 
		$_SESSION["time_cm_post"] = time();
		if($multi_id)
			$ro_cm_inr=$DB->query("INSERT INTO ".$conf['prefix']."comment (cm_multi,cm_date,cm_user_id,cm_content) VALUES (".$multi_id.",'".date("Y-m-d H:i:s")."','".$user_id."','".$content."')");
		elseif($media_id)
			$ro_cm_inr=$DB->query("INSERT INTO ".$conf['prefix']."comment (cm_media,cm_date,cm_user_id,cm_content) VALUES (".$media_id.",'".date("Y-m-d H:i:s")."','".$user_id."','".$content."')");
		
		if($ro_cm_inr) 
			echo "<font color=blue><b>".$lang['comment_sent']."</b></font>";	
		else 
			echo "<font color=blue><b>".$lang['error'].". ".$lang['try_again']."</b></font>";
			echo "<br>".box_list_comment($multi_id,$media_id);

	  }	
	}
}

if($_POST['ajaxtype']=="download" && $_POST['m_id'] && $_POST['encrypt_id']){
	$type=urldecode($_POST['type']);
	$multi_id=urldecode($_POST['multi_id']);
	$m_id=urldecode($_POST['m_id']);
	$en_id=urldecode($_POST['encrypt_id']);
	$where='';
	if($multi_id)
		$check=$func->encode_down($multi_id);
	else
		$check=$func->encode_down($m_id);
	if($conf['must_login_to_download'] && !$logged_in){
		$url='login_to_download';
		$show_down='<b>'.$lang['must_login_to_download'].'</b>';
	}elseif(!$conf['must_login_to_download'] || ($conf['must_login_to_download'] && $logged_in)){
		if($check==$en_id){
			if($type=="epi" && $multi_id) $where="AND m_multimedia={$multi_id}";
		$DB->query("UPDATE ".$conf['prefix']."media SET m_downloaded=m_downloaded+1,m_downloaded_month=m_downloaded_month+1 WHERE m_id={$m_id} {$where}");
		$se_url=$DB->query("SELECT m_title,m_url,m_is_local,m_type FROM {$conf['prefix']}media WHERE m_id={$m_id} {$where}");
		$ro_url=$DB->fetch_row($se_url);
				
			if ($ro_url['m_is_local']){
					$url=$func->get_server($ro_url['m_is_local'],$ro_url['m_url']);
			}
			else{
				$type_qr=$DB->query("SELECT player_isgrab FROM ".$conf['prefix']."player WHERE player_id=".$ro_url['m_type']);
				$type_chek=$DB->fetch_row($type_qr);
				$url=($type_chek['player_isgrab'])?($func->grab_link($ro_url['m_url'],true)):$ro_url['m_url'];
			}
		}
		else $url="nolink";
	
			if($type=='epi'){
				if($url!="nolink") $show_down="<b>".$lang['part']." ".$ro_url['m_title']."</b>";
				else $show_down="<b>".$url."</b>";
			}
			elseif($type=='song')
				$show_down="<img src={TPL_LINK}/img/click_download.png border=0>";
	}			
			$ju= $tpl->get_tpl('box_download');
			$ju = $tpl->assign_vars($ju,
				array(
					'LANG_DOWNLOAD'	=> $lang['download'],
					'LANG_CLOSE'	=> $lang['close'],
					'LINK_DOWNLOAD'	=>	$url,
					'DOWNLOAD'		=>  $show_down,
				)
			);	
			
	echo $tpl->parse_tpl($ju);
}

if($_POST['ajaxtype']=="multimedia"){
	$id=urldecode($_POST['id']);
	$type_multi=urldecode($_POST['type_multi']);
	$page=intval($_POST['page']);
	if(!$page) $page=1;
	$number=intval($_POST['num_per']);
	if(!$number) $number=9;
	if($_POST['kind']=="viewpage" && $id)
		echo box_multimedia($type_multi,1,$number,$id,3,$page);
	

}

if($_POST['ajaxtype']=="get_mypl"){
	$user_id=$_SESSION['ses_user_id'];
	$html=$tpl->get_tpl("box_myplaylist");
	$qr=$DB->query("SELECT * FROM {$conf['prefix']}playlist WHERE pl_user_id={$user_id}");
	$t['row'] = $tpl->get_block_from_str($main,'list_pl_row',1);
	while($r=$DB->fetch_row($qr)){
		$html.= $tpl->assign_vars($t['row'],
			array(
				'mypl.ID' => $r['pl_id'],
				'mypl.NAME' => $r['pl_name'],
			)
		);
		
	}
	$html = $tpl->assign_blocks_content($html,array(
		'list_pl'	=>	$html
		)
	);
	echo $tpl->parse($html);
}

if($_POST['ajaxtype']=="playlist"){
$media_id=intval($_POST['media_id']);
$pl_id=intval($_POST['pl_id']);
$type=$_POST['type'];
	if(!$logged_in){
		$pl_contents=$_SESSION['ses_playlist'];
		if($type=="add"){
			if(!$pl_contents) $_SESSION['ses_playlist'] = $media_id;
			else {
				$ro = split(',',$pl_contents);
				if (!in_array($media_id,$ro)) $_SESSION['ses_playlist'] = $pl_contents.','.$media_id;
			}
		}elseif($type=="remove"){
			if($media_id == $pl_contents) $_SESSION['ses_playlist'] = '';
			else{
				$ro = split(',',$pl_contents);
				if (in_array($media_id,$ro)) {
					unset($ro[array_search($media_id,$ro)]);
					$str = implode(',',$ro);
					$_SESSION['ses_playlist'] = $str;
				}
			}
		}
	}
	else{
		if($type && $pl_id){
		  $pl_contents=$func->get_data("playlist",$pl_id,"pl_contents");
			if($type=="add" && $media_id){
			
				if(!$pl_contents) $pl_contents = $media_id;
				else {
					$ro = split(',',$pl_contents);
					if (!in_array($media_id,$ro)) $pl_contents = $pl_contents.','.$media_id;
				}
				$q=$DB->query("UPDATE ".$conf['prefix']."playlist SET pl_contents='{$pl_contents}' WHERE pl_id={$pl_id}");
			}elseif($type=="remove"){
				if($media_id){
					if($media_id == $pl_contents) $pl_contents = '';
					else{
						$ro = split(',',$pl_contents);
						if (in_array($media_id,$ro)) {
							unset($ro[array_search($media_id,$ro)]);
							$str = implode(',',$ro);
							$pl_contents = $str;
						}
					}
					$q=$DB->query("UPDATE ".$conf['prefix']."playlist SET pl_contents='{$pl_contents}' WHERE pl_id={$pl_id}");
				}
				else{
					$func->del_local_img("playlist",$pl_id);
				 	$DB->query("DELETE FROM {$conf['prefix']}playlist WHERE pl_id={$pl_id}");
				 }
			}
		}
		elseif(!$type && $media_id && !$pl_id){
			$user_id=$_SESSION['ses_user_id'];
			$htm='';
			$ro=$tpl->get_tpl("box_myplaylist");
			$qr=$DB->query("SELECT * FROM {$conf['prefix']}playlist WHERE pl_userid='{$user_id}'");
			$t['row'] = $tpl->get_block_from_str($ro,'list_pl_row',1);
			if($DB->num_rows($qr)){
			
				while($r=$DB->fetch_row($qr)){
					$htm.= $tpl->assign_vars($t['row'],
						array(
							'mypl.ID' => $r['pl_id'],
							'mypl.NAME' => $r['pl_name'],
						)
					);
					
				}
			}
	

			$ro = $tpl->assign_blocks_content($ro,array(
					'list_pl'	=>	$htm
					)
			);
			$ro=$tpl->assign_vars($ro,array(
						'media.ID' => $media_id,
					)
			);
			echo $tpl->parse_tpl($ro);
			exit();
		}
	}
echo box_playlist();
}


if($_POST['ajaxtype']=="qplay") {
	if (!$logged_in && $conf['must_login_to_play']) 
		die("<center><b>{$lang['must_login_to_view']}</b></center");
	$id = $_POST['media_id'];
		$DB->query("UPDATE ".$conf['prefix']."media SET m_viewed=m_viewed+1, m_viewed_month=m_viewed_month+1 WHERE m_id ={$id}");
		$cached['quick_play_player'][$id] = $func->get_player($id);
	echo $cached['quick_play_player'][$id];
	exit();
}

if($_POST['ajaxtype']=="tivi") {
	if (!$logged_in && $conf['must_login_to_play']) 
		die("<center><b>{$lang['must_login_to_view']}</b></center");
    $tivi_id =$_POST['tivi_id'];
	$type_tivi=$_POST['type_tivi'];
	 if($type_tivi==1){
	 $url='http://www.vtc.com.vn/XMLFile.aspx?id='.$tivi_id.'&tp=l';
	 $xml=$func->get_by_curl($url,'','','http://www.vtc.com.vn/playstream.swf');
	 preg_match('#<hostUrl>(.*?)</hostUrl>#',$xml,$live);
	 preg_match('#<filename>(.*?)</filename>#',$xml,$title); 
			$player='<embed type="application/x-shockwave-flash" src="'.$conf['web_url'].'/mediaplayer.swf" style="" id="mpl" name="mpl" quality="high" allowscriptaccess="always" allowfullscreen="true" flashvars="height=410&amp;width=500&amp;file='.$live[1].'&amp;id='.$title[1].'&amp;showicons=true&amp;shownavigation=true&amp;showstop=true&amp;showdigits=true&amp;autostart=true&amp;enablejs=true&amp;volume=100" height="410" width="500">';
/*
$player='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="myFlashContent" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0"  width="480" height="378">  <param name="allowDomain" value="always">  <param name="allowScriptAccess" value="always">  <param name="allowFullScreen" value="true" />  <param name="movie" value="/playstream.swf" />  <param name="quality" value="high" />  <param name="flashvars" value="id=10&tp=l"  />  <param name="bgcolor" value="#000000" />  <embed src="http://www.vtc.com.vn/playstream.swf" flashvars="id='.$tivi_id.'&tp=l" quality="high" name="myFlashContent" allowFullScreen="true"  allowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"      type="application/x-shockwave-flash" width="480" height="378"></embed></object>';	
*/
	}
	elseif(in_array($type_tivi,array('hbo','espn'))){
		if($type_tivi=='hbo'){
			$data=$func->get_by_curl("http://www.tvchannelsfree.com/watch/1386/HBO-Video.html");
				preg_match('#flashvars="file=.*\&streamer=.*\&autostart=true"#i',$data,$flash_vars);
			$player='<embed src="'.$conf['web_url'].'/mplayer.swf" width="500" height="400" bgcolor="undefined" allowscriptaccess="always" allowfullscreen="true" '.$flash_vars[0].'/>';
		}
		if($type_tivi=='espn'){
			$data=$func->get_by_curl("http://www.tvchannelsfree.com/watch/1545/ESPN.html");
			preg_match('#<param name=[\'"]FileName[\'"] value=[\'"](.*?)[\'"]>#i',$data,$mms);
			$player='<object id="MediaPlayer" width="500" height="400" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" standby="Please Wait ..." type="application/x-oleobject">
		<param name="FileName" value="'.$mms[1].'"><param name="Autostart" value="true"><param name="enableContextMenu" value="false"><param name="ShowControls" value="true"><param name="ShowDisplay" value="false"><param name="ShowStatusBar" value="true"><param name="ShowTracker" value="false"><param name="Volume" value="0">
		<embed type="application/x-mplayer2" src="'.$mms[1].'" name="MediaPlayer" width="500" height="400" Autostart="1" enableContextMenu="0" ShowControls="1" ShowDisplay="0" ShowStatusBar="1" ShowTracker="0" Volume="0" bgcolor="#000000"></embed>
	</object>
';
		}
	}

	$roju=$tpl->get_tpl("watch_television");
			$roju = $tpl->assign_vars($roju,array(
				'tivi.CHANNEL'	=> $title[1],
				)
			);
			$roju = $tpl->assign_blocks_content($roju,array(
				'player'	=> $player,
				)
			);
	echo $tpl->parse_tpl($roju);
}

if($_POST['ajaxtype']=="video") {
$video_id=$_POST['video_id'];
$doc = new DOMDocument( "1.0", 'UTF-8' );
$doc->formatOutput = true;
$file_xml='source/autopro.xml';
@$doc->load($file_xml);
  $keys = $doc->getElementsByTagName( "key" );
		   foreach( $keys as $key )
		  {
		  	  $ids = $key->getElementsByTagName( "id" );
			  $id = $ids->item(0)->nodeValue;
			  $names = $key->getElementsByTagName( "name" );
			  $name = $names->item(0)->nodeValue;
			  $locations = $key->getElementsByTagName( "location" );
			  $location = $locations->item(0)->nodeValue;
			  $images = $key->getElementsByTagName( "image" );
			  $image = $images->item(0)->nodeValue;
			 
			  if($video_id==$id){
			  $url_flv=$location;
			  $video_title=$name;
			  $video_img=$image;
			  break;
			  }
			  
		}
		if($url_flv && $video_title){
			$ro=$tpl->get_tpl("video_playing");	
			 $video_title_ascii=$func->utf8_to_ascii($video_title);
			 $qr=$DB->query("select * from {$conf['prefix']}player where player_name='flv'");
			 $ro1=$DB->fetch_row($qr);
			 preg_match('@^(?:http://)?([^/]+)@i',$video_img, $local);
			 $link_direct="http://".$local[1].$url_flv;
			 $player=$func->unhtmlchars($ro1['player_html']);
			 $player=str_replace("{WIDTH}",$ro1['player_width'],$player);
			 $player=str_replace("{HEIGHT}",$ro1['player_height'],$player);
			 $player=str_replace("{URL}",$link_direct,$player);
			$ro=$tpl->assign_vars($ro,array(
					'video.TITLE'	=> $video_title,
					'video.PLAYER'	=> $player,
					'video.URL_DOWNLOAD'	=> $link_direct,
					'video.LINK'	=> $func->change_link("video-detail",$video_id,$func->title_2_ascii($video_title_ascii)),
			 	)
			);
			$ro=$tpl->parse_tpl($ro);
        }
		else
			$ro=$lang['no_data'];
	echo $ro;
}

if($_POST['ajaxtype']=="load_server_epi") {
$server_id=intval($_POST['server_id']);
$multi_id=intval($_POST['multi_id']);
$sql_epi=$DB->query("SELECT * FROM {$conf['prefix']}media WHERE m_multimedia={$multi_id} AND m_server={$server_id} ORDER BY CAST(m_title as SIGNED)");
$total_eps = $DB->num_rows($sql_epi);
$ro= $tpl->get_tpl('episode_field_ajax');
$html='';
$t['row'] = $tpl->get_block_from_str($ro,'epi_row',1);
		if($total_eps){
			$i = 0;
			$overflow=($total_eps>30)?'height:300px; overflow:auto;':'';
			while($epi=$DB->fetch_row($sql_epi)){
				$i++;
				$arr_epi[$i]['id']=$epi['m_id'];
				$arr_epi[$i]['title']=$epi['m_title'];
			  $tr = (fmod($i,5) == 1)?'<tr></tr>':'';	
			  if($current_epi && ($current_epi==$epi['m_id']))
				$class_cur_epi="cl_part_cur";
			  else
				$class_cur_epi="cl_part";
			  if($conf['epi_noajax'])
				$epi_div="<div id=\"epi_".$i."\" class=\"".$class_cur_epi."\" align=\"center\"><a href=\"".$func->change_link("movie_epi",$multi_id,"",$epi['m_id'])."\"><b>» ".$lang['part']." ".$epi['m_title']."</b></a></div>";
			  else
				$epi_div="<div id=\"epi_".$i."\" class=\"cl_part\" align=\"center\"><a href=\"#\" onclick=\"return Get_Player('".$multi_id."','".$epi['m_id']."','".$total_eps."','".$i."');\"><b>» ".$lang['part']." ".$epi['m_title']."</b></a></div>";
				$html .= $tpl->assign_vars($t['row'],
					array(
						'epi.TR'		=> $tr,
						'epi.DIV'		=> $epi_div,
					)
				);
			}

		}
		else{
			$html="<center><font color=blue>".$lang['updating']."</font></center><br>";
		}
		
		$ro = $tpl->assign_blocks_content($ro,array(
				'list_epi'	=> $html,
				'epi_noajax' => $show_epi_playing,
				)
		);
		$ro = $tpl->assign_vars($ro,
				array(
					'movie.OVERFLOW'  =>$overflow,
				)
			);
$ro=$tpl->parse_tpl($ro);
echo $ro;

}
if($_POST['ajaxtype']=="load_server_download"){
$server_id=intval($_POST['server_id']);
$movie_id=intval($_POST['multi_id']);
$sql_epi=$DB->query("SELECT * FROM {$conf['prefix']}media WHERE m_multimedia={$movie_id} AND m_server={$server_id} ORDER BY CAST(m_title as SIGNED)");
$total_eps = $DB->num_rows($sql_epi);
	if($total_eps){
			if(!$conf['must_login_to_download'] || ($conf['must_login_to_download'] && $logged_in)){
				$download_block='<div style="width:240px; height:64px;" align="center">
						<form method="post" name="get_download_epi" onsubmit="get_download(this,\'epi\'); return false;">
						<b>'.$lang['choose_epi_down'].' </b><br />
						<select id="select_down" name="select_down">';
				while($epi=$DB->fetch_row($sql_epi)){
						$download_block.= "<option value='".$epi['m_id']."'>".$lang['part']." ".$epi['m_title']."</option>";
					 }
				$download_block.='</select>
						<input type="hidden" value="'.$func->encode_down($movie_id).'" id="id_down" name="id_down" />
						<input type="hidden" value="'.$movie_id.'" id="movie_id"  name="movie_id" />
						<input type="submit" value="Download" />
						</form>
						</div><br /><font color="red"><b>Nếu bạn không download được <a href="'.$conf['web_url'].'/huongdan_download.html" title="Click vào đây để xem hướng dẫn" target="_blank">Click vào đây để xem hướng dẫn</a></b>
</font>'; 
			}
			elseif($conf['must_login_to_download'] && !$logged_in) $download_block='<b>'.$lang['must_login_to_download'].'</b>';
	}
	else $download_block='';
echo $download_block;
	
}

if($_POST['ajaxtype']=="send_sms"){
function curl($url,$var='',$header=0,$foll=0,$cookie=''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (iPhone,U; CPU iPhone OS 2_2_1 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) version/3.1.1 Mobile/5H11 Safari/525.20');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $foll);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
if($var){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$var);
}
if($cookie) curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cook_ss.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cook_ss.txt");
curl_setopt ($ch, CURLOPT_HEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
ob_start();     
$result=curl_exec ($ch);
ob_end_clean(); 
curl_close ($ch);
return $result;
}	
function encode_special($n,$x=0) {
	$special_array = array('%' => '%25', '&' => '%26', '\'' => '%27', '(' => '%28', ')' => '%29', '*' => '%2A', '+' => '%2B', ',' => '%2C', '-' => '%2D', '.' => '%2E', '/' => '%2F', ':' => '%3A', ';' => '%3B', '<' => '%3C', '=' => '%3D', '>' => '%3E', '?' => '%3F', '@' => '%40', '[' => '%5B', '\\' => '%5C', ']' => '%5D', '^' => '%5E', '_' => '%5F', '`' => '%60', '{' => '%7B', '|' => '%7C', '}' => '%7D', '~' => '%7E', '\n' => '%0A');
	foreach ($special_array as $key => $value){
	 if($x) $n = str_replace($value,$key,$n);
	 else $n = str_replace($key,$value,$n);
	}
	return $n;
}	
function utf8_ascii($str) {
	$chars = array(
	 'a'	=>	array('ấ','ầ','ẩ','ẫ','ậ','ắ','ằ','ẳ','ẵ','ặ','á','à','ả','ã','ạ','â','ă'),
	 'A'	=>	array('Ấ','Ầ','Ẩ','Ẫ','Ậ','Ắ','Ằ','Ẳ','Ẵ','Ặ','Á','À','Ả','Ã','Ạ','Â','Ă'),
	 'e' =>	array('ế','ề','ể','ễ','ệ','é','è','ẻ','ẽ','ẹ','ê'),
	 'E'	=>	array('Ế','Ề','Ể','Ễ','Ệ','É','È','Ẻ','Ẽ','Ẹ','Ê'),
	 'i'	=>	array('í','ì','ỉ','ĩ','ị'),
	 'I' =>	array('Í','Ì','Ỉ','Ĩ','Ị'),
	 'o'	=>	array('ố','ồ','ổ','ỗ','ộ','ớ','ờ','ở','ỡ','ợ','ó','ò','ỏ','õ','ọ','ô','ơ'),
	 'O'	=>	array('Ố','Ồ','Ổ','Ô','Ộ','Ớ','Ờ','Ở','Ỡ','Ợ','Ó','Ò','Ỏ','Õ','Ọ','Ô','Ơ'),
	 'u'	=>	array('ứ','ừ','ử','ữ','ự','ú','ù','ủ','ũ','ụ','ư'),
	 'U' =>	array('Ứ','Ừ','Ử','Ữ','Ự','Ú','Ù','Ủ','Ũ','Ụ','Ư'),
	 'y'	=>	array('ý','ỳ','ỷ','ỹ','ỵ'),
	 'Y'	=>	array('Ý','Ỳ','Ỷ','Ỹ','Ỵ'),
	 'd'	=>	array('đ'),
	 'D' => 	array('Đ'),
	);
	foreach ($chars as $key => $arr) 
	 foreach ($arr as $val)
	 $str = str_replace($val,$key,$str);
	return $str;
}

function login($nick,$pass){
	global $func,$sms_redir;
	$nick = encode_special($nick);
	$pass = encode_special($pass);
	$var_acc="nickname={$nick}&password={$pass}";
	$post="joy=1&link=".urlencode("http://mjoy.com/m/login.htm")."&vars=".urlencode($var_acc)."&head=1&foll=1&cook=";
	$data=$func->get_by_curl($sms_redir,true,$post);
	preg_match("#Set-Cookie:(.*?)\\n#s",$data, $res);
	$cookie=trim($res[1]);
	preg_match('#<a href=[\'"]\/m\/messages\/(.*?)\/index\.htm[\'"]><img src=[\'"]\/m\/img\/main\/messages.gif[\'"] alt=[\'"]Free Text[\'"]\/><\/a>#',$data,$id);
	$sid=$id[1];
	if(!$sid) die();
	$out = array('cookie' => $cookie, 'pass' => $pass, 'nick' => $nick, 'sid' => $sid);
	return $out;
}

function send_sms($num,$content,$count){
	global $out,$func,$sms_redir;
	
	if(!$num) die('Chưa nhập số gửi đến');
	if(!$content) die('Nội dung tin nhắn rỗng');
	$post="joy=1&link=".urlencode("http://mjoy.com/m/messages/{$out['sid']}/new.htm")."&vars=&head=1&foll=1&cook=".urlencode($out['cookie']);
	$new=$func->get_by_curl($sms_redir,true,$post);
	//$new=curl("http://mjoy.com/m/messages/{$out[sid]}/new.htm",'',1,1,$out['cookie']);
	preg_match("#Location:(.*?)\\n#s",$new, $local);
	$create=str_replace("adreminder","new",trim($local[1]));
	$post="joy=1&link=".urlencode($create)."&vars=&head=1&foll=0&cook=";
	$text=$func->get_by_curl($sms_redir,true,$post);
	//$text=curl($create,'',1);
	preg_match('#<textarea class=[\'"]input textarea[\'"] name=[\'"](.*?)[\'"]></textarea>#',$text,$name_text);
	$mess_name=$name_text[1];
	preg_match('#<input type=[\'"]hidden[\'"] name=[\'"]name[\'"]   value=[\'"](.*?)[\'"]>#',$text,$name_value);
	$name = $name_value[1];
	preg_match('#<input type=[\'"]hidden[\'"] name=[\'"]number[\'"]   value=[\'"](.*?)[\'"]>#',$text,$number_value);
	$number = $number_value[1];
	preg_match('#<input type=[\'"]hidden[\'"] name=[\'"]from[\'"]   value=[\'"](.*?)[\'"]>#',$text,$from_value);
	$from = $from_value[1];
	$extra = "\n";
	$mes_content = encode_special(utf8_ascii($content).$extra);
	$to_number=encode_special(str_replace('+','@$roluvju$@',$num));
	$var_send="name={$name}&number={$to_number}&from={$from}&recipient={$to_number}&{$mess_name}={$mes_content}";
	$post_send="joy=1&link=".urlencode("http://mjoy.com/m/messages/{$out['sid']}/new.htm")."&vars=".urlencode($var_send)."&head=1&foll=1&cook=".urlencode($out['cookie']);
	$send=$func->get_by_curl($sms_redir,true,$post_send);
	//$send=curl("http://mjoy.com/m/messages/{$out[sid]}/new.htm",$var_send,1,1,$out['cookie']);
	if(preg_match('/Message sent/i',$send)) {
	 echo "Gửi thành công. Bạn còn ".(10-(intval($count)+1))."/10 tin";
	 	return true;
	}elseif(preg_match('/Recipient missing/i',$send)){
	 echo "Chưa nhập số gửi đến";
	 	return false;
	}elseif(preg_match('/Recipient number invalid/i',$send)){
	 echo "Số gửi đến không hợp lệ";
	 	return false;
	}elseif(preg_match('/Message is empty/i',$send)){
	 echo "Nội dung tin nhắn rỗng";
	 	return false;
	}
}	

if(!$logged_in) die('Bạn chưa đăng nhập');
if(!$_POST['sms_num']) die('Chưa có số gửi đến');
if(!$_POST['sms_mes']) die('Chưa có nội dung gửi đi');
		$sms_number=addslashes(trim($_POST['sms_num']));	
		$sms_mess=stripslashes(trim($_POST['sms_mes']));
		$sms_redir='http://haiduongvui.com/index%281%29.php';
		$qr=$DB->query("SELECT u_sms FROM {$conf['prefix']}user WHERE u_id=".$_SESSION['ses_user_id']);
		$count_sms=$DB->fetch_row($qr);
		if($count_sms['u_sms']<10){
				$out=login("roluvju","mothaibaabc");
				$vl=send_sms($sms_number,$sms_mess,$count_sms['u_sms']);
						if($vl)
							$up=$DB->query("UPDATE {$conf['prefix']}user SET u_sms=u_sms+1 WHERE u_id=".$_SESSION['ses_user_id']);
		}			
		else
			echo "Bạn chỉ được gửi 10 tin/ngày";
	
	

}
?>